package com.supermarket.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 数据库连接工具类
 * 负责管理MySQL数据库连接
 */
public class DatabaseUtil {
    private static String DB_URL;
    private static String DB_USERNAME;
    private static String DB_PASSWORD;
    private static String DB_DRIVER;

    // 静态初始化块，加载配置文件
    static {
        loadConfig();
    }

    /**
     * 加载数据库配置
     */
    private static void loadConfig() {
        Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream("config.properties")) {
            props.load(fis);
            DB_URL = props.getProperty("db.url");
            DB_USERNAME = props.getProperty("db.username");
            DB_PASSWORD = props.getProperty("db.password");
            DB_DRIVER = props.getProperty("db.driver");

            // 加载MySQL驱动
            Class.forName(DB_DRIVER);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            // 使用默认配置
            DB_URL = "jdbc:mysql://localhost:3306/supermarket_management?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8";
            DB_USERNAME = "root";
            DB_PASSWORD = "123456";
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 获取数据库连接
     * 
     * @return Connection对象
     * @throws SQLException SQL异常
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
    }

    /**
     * 关闭数据库连接资源
     * 
     * @param conn 连接对象
     * @param ps   预处理语句对象
     * @param rs   结果集对象
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭数据库连接资源（重载方法）
     * 
     * @param conn 连接对象
     * @param ps   预处理语句对象
     */
    public static void close(Connection conn, PreparedStatement ps) {
        close(conn, ps, null);
    }

    /**
     * 关闭数据库连接资源（重载方法）
     * 
     * @param conn 连接对象
     */
    public static void close(Connection conn) {
        close(conn, null, null);
    }

    /**
     * 测试数据库连接
     * 
     * @return 连接是否成功
     */
    public static boolean testConnection() {
        try (Connection conn = getConnection()) {
            return conn != null && !conn.isClosed();
        } catch (SQLException e) {
            System.err.println("数据库连接测试失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取数据库配置信息（用于调试）
     */
    public static void printConfig() {
        System.out.println("数据库配置信息:");
        System.out.println("URL: " + DB_URL);
        System.out.println("Username: " + DB_USERNAME);
        System.out.println("Driver: " + DB_DRIVER);
    }
}
